package dht.server;

import java.util.Vector;

import dht.IMetaServerRouteTable;
import dht.IRoutineHandler;
import dht.IServer;
import dht.entity.GlobalVariables;
import dht.entity.Message;
import dht.entity.MessageType;
import dht.entity.NodeInfo;
import dht.throwable.DhtException;
import dht.util.IdGenerator;

public class MetaServerRoutineHandlerImpl implements IRoutineHandler {

	protected int loadBalancingPeriod;
	protected IServer server;
	protected IMetaServerRouteTable routeTable;

	public MetaServerRoutineHandlerImpl(IServer server,
			IMetaServerRouteTable routeTable) {
		this.loadBalancingPeriod = GlobalVariables.loadBalancingPeriod;
		this.server = server;
		this.routeTable = routeTable;
	}

	protected void loadBalancing() {
		Message msg = null;
		msg = new Message(IdGenerator.genTransactionId(), MessageType.MOV_REQ,
				server.getLocalInfo());
		NodeInfo moveFromServerInfo = new NodeInfo();
		NodeInfo moveToServerInfo = new NodeInfo();
		Vector<Integer> movementVnodeIds = new Vector<Integer>();
		if (!routeTable.startLoadBalancing(moveFromServerInfo,
				moveToServerInfo, movementVnodeIds)) {
			System.out.println("no need to do balancing");
			return;
		}
		msg.setMoveFromServerInfo(moveFromServerInfo);
		msg.setMoveToServerInfo(moveToServerInfo);
		msg.setMovementVnodeIds(movementVnodeIds);
		try {
			server.handleInitiativeTransaction(msg.getMoveFromServerInfo(),
					msg, false);
		} catch (DhtException e) {
			e.printStackTrace();
			return;
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(loadBalancingPeriod);
			} catch (InterruptedException e) {
				e.printStackTrace();
				continue;
			}
			loadBalancing();
		}
	}

}
